import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Not, Repository } from 'typeorm';
import { Notices } from './notices.entity';
import { NoticeIsDeleteEnum, NoticeReadTypeEnum } from './notices.enum';

@Injectable()
export class NoticesService {
  constructor(
    @InjectRepository(Notices)
    private repository: Repository<Notices>,
  ) {}


  async getNotRead(wx_user: string): Promise<number>{
    let total = await this.repository.query(`
      select count(1) as total from notices
      where wx_user = ? and is_read = ? and is_delete = ? and (notices.effect_time is null or notices.effect_time <= now())
    `,[wx_user, NoticeReadTypeEnum.not_read, NoticeIsDeleteEnum.no])
    return Number(total?.[0]?.total || 0)
  }

  findAll_By_WxUser(wx_user: string, take: number, skip: number): Promise<Notices[]> {
    return this.repository.query(`
      select notices.*, reject_reason.reason from notices
      left join reject_reason on reject_reason.id = notices.reject_reason
      where wx_user = ? and (notices.effect_time is null or notices.effect_time <= now())
      order by id desc
      limit ?,?
    `,[wx_user, skip, take])
  }

  /**
   * 批量阅读通知
   * @param ids
   */
  async readNotices(ids:number[]){
    return await this.repository.update({id:In(ids)},{is_read: NoticeReadTypeEnum.is_read})
  }

  findAll(): Promise<Notices[]> {
    return this.repository.find();
  }

  findOne(id: any): Promise<Notices> {
    return this.repository.findOne(id);
  }

  async remove(id: number): Promise<void> {
    await this.repository.delete(id);
  }

  async create(data: Notices): Promise<Notices> {
    let saveData = new Notices()
    saveData.answer_id = data.answer_id
    saveData.create_time = new Date()
    saveData.type = data.type
    saveData.video_id = data.video_id
    saveData.wx_user = data.wx_user
    return await this.repository.create(saveData)
  }
}
